package com.atguigu.tingshu.album.receiver;

import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.constant.RabbitConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: AlbumInfoReceiver
 * Package: com.atguigu.tingshu.album.receiver
 * Description:专辑消息消费类
 */
@Slf4j
@Component
public class AlbumInfoReceiver {
    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 监听删除redis中数据的消息
     */
    @SneakyThrows
    @RabbitListener(queues = RabbitConstant.ALBUMINFO_REMOVE_QUEUE)
    public void removeAlbumInfoFromRedis(Message message, Channel channel){
        Long deliveryTag = null;
        try {
            //获取消息编号
            deliveryTag= message.getMessageProperties().getDeliveryTag();
            //获取消息内容
            Long albumId = Long.parseLong(new String(message.getBody()));
            //拼接缓存key
            String cacheKey = "getAlbumInfo:[" +albumId + "]";
            //双删保证删除redis中的数据
            //第一次删(设置很短的过期时间)
            redisTemplate.expire(cacheKey,1, TimeUnit.SECONDS);
            //第二次删
            redisTemplate.delete(cacheKey);
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            e.printStackTrace();
            if (message.getMessageProperties().getRedelivered()){
                //消息第二次执行失败
                log.error("消息连续两次执行失败.....记录数据库");
                channel.basicReject(deliveryTag,false);
            }else {
                //消息第一次执行失败
                log.error("消息第一次投递失败,重新投递.....");
                channel.basicReject(deliveryTag,true);
            }
        }

    }
}
